/**
 * @author renbangjie renbangjie@126.com
 * @date 2015-10-9 上午9:09:12
 * @version V1.0
 * <b>Copyright (c)</b> 2014医信金融信息服务（上海）有限公司-版权所有<br/>
 */
package com.yjd.comm.util;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yjd.comm.funds.dto.QuickPayConfigDTO;
import com.yjd.comm.funds.dto.QuickPayDTO;
import com.yjd.comm.funds.dto.RechOrderDTO;
import com.yjd.comm.funds.enums.OriginRechChannel;
import com.yjd.comm.funds.enums.RechChannel;
import com.yjd.comm.funds.model.RechargeOrderModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.vo.Constant.SysParamKeyEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * 美分期充值工具类
 */
public class QuickPayUtils {

    private final static Logger logger = Logger.getLogger(QuickPayUtils.class);

    /**
     * 生成调用第三方订单信息
     *
     * @param rechOrderDTO
     * @param dbOrder
     * @return QuickPayOrder
     * @throws Exception
     */
    public static QuickPayDTO generateOrder(RechOrderDTO rechOrderDTO, RechargeOrderModel dbOrder) throws Exception {

        if (rechOrderDTO == null || dbOrder == null) {
            FrameUtil.throwBaseException1("参数异常");
        }
        QuickPayDTO quick = QuickPayUtils.generator(rechOrderDTO);

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("pay_order", dbOrder.getOrder_id().toString());
        paramMap.put("pay_title", rechOrderDTO.getMemo());
        paramMap.put("pay_money", dbOrder.getPrice().toString());
        paramMap.put("bank_code", rechOrderDTO.getBank_code());
        paramMap.put("bank_card_no", rechOrderDTO.getBank_no());
        paramMap.put("bank_card_idname", rechOrderDTO.getRealName());
        paramMap.put("bank_card_idcard", rechOrderDTO.getCertNo());
        paramMap.put("mpNumber", rechOrderDTO.getMpNumber());
        paramMap.put("pay_url_return", quick.getReturnUrl());
        paramMap.put("pay_url_notice", quick.getCallBackUrl());
        paramMap.put("user_id", dbOrder.getUser_id().toString());
        paramMap.put("rech_type",dbOrder.getOrder_type()==null?"0":dbOrder.getOrder_type().toString());//默认为0
        paramMap.put("client", rechOrderDTO.getRechChannel().getLable());
        paramMap.put("parameter",
                dbOrder.getUser_id() + "," + rechOrderDTO.getUsername() + ","
                        + rechOrderDTO.getRegDate());
        paramMap.put("rech_channel", rechOrderDTO.getRechChannel().toString());
        String appMsg = JSONUtils.toJSONString(paramMap);
        if (StringUtils.isBlank(appMsg)) {
            FrameUtil.throwBaseException1("数据异常");
        }
        quick.setAppMsg(CryptAES.AES_Encrypt(SecurityCode.md5(quick.getKey()), appMsg));
        return quick;
    }

    /**
     * 解析回调参数
     *
     * @param resultMap
     * @return QuickPayOrder
     * @throws Exception
     */
    public static QuickPayDTO parseOrder(Map<String, Object> resultMap) throws Exception {
        if (resultMap == null) {
            FrameUtil.throwBaseException1("参数异常");
        }
        String sysOrderId = (String) resultMap.get("sysOrderId");
        String finishTime = (String) resultMap.get("finishTime");
        if (StringUtils.isBlank(sysOrderId)
                || !NumberUtils.isNumber(sysOrderId)
                || StringUtils.isBlank(finishTime)
                || !NumberUtils.isNumber(finishTime)) {
            FrameUtil.throwBaseException1("参数异常");
        }

        QuickPayDTO quickOrder = new QuickPayDTO();
        quickOrder.setTransId((String) resultMap.get("transId"));
        quickOrder.setSysOrderId(sysOrderId);
        quickOrder.setStatus((String) resultMap.get("status"));
        quickOrder.setResultMsg((String) resultMap.get("resultMsg"));
        quickOrder.setFinishTime(finishTime);
        quickOrder.setDesc((String) resultMap.get("desc"));
        quickOrder.setOrderAmount((String) resultMap.get("orderAmount"));
        quickOrder.setBankCode((String) resultMap.get("bankCode"));
        quickOrder.setBankCardNo((String) resultMap.get("bankCardNo"));
        quickOrder.setCertNo((String) resultMap.get("certNo"));
        quickOrder.setRealName((String) resultMap.get("realName"));
        quickOrder.setMemo((String) resultMap.get("memo"));
        quickOrder.setMpNumber((String) resultMap.get("mpNumber"));
        quickOrder.setUser_id((String) resultMap.get("user_id"));
        quickOrder.setChannel((String) resultMap.get("pay_channel"));
        quickOrder.setRechType((String) resultMap.get("rech_type"));
        quickOrder.setIsConsole(false);
        return quickOrder;
    }

    /**
     * 解析参数
     *
     * @param appMsg
     * @return Map<String,Object>
     * @throws Exception
     */
    public static Map<String, Object> resultMap(String appMsg) throws Exception {
        if (StringUtils.isBlank(appMsg)) {
            FrameUtil.throwBaseException1("参数异常");
        }
        String message = CryptAES.AES_Decrypt(SecurityCode.md5(QuickPayUtils.getConfig().getKey()), appMsg);
        if (StringUtils.isBlank(message)) {
            FrameUtil.throwBaseException1("无法解析的请求");
        }
        JSONObject resultMsg = JSONObject.parseObject(message);
        if (resultMsg == null) {
            FrameUtil.throwBaseException1("参数有误");
        }
        JSONObject statusMap = resultMsg.getJSONObject("AppResult");
        JSONObject backMap = resultMsg.getJSONObject("PayBack");
        JSONObject paramMap = resultMsg.getJSONObject("RequestParms");
        if (statusMap == null || paramMap == null || backMap == null) {
            FrameUtil.throwBaseException1("参数有误");
        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("resultMsg", statusMap.getString("Msg"));
        resultMap.put("transId", backMap.getString("pay_trace"));
        resultMap.put("status", backMap.getString("pay_code"));
        resultMap.put("finishTime", backMap.getString("finish_time"));
        resultMap.put("orderAmount", backMap.getString("pay_money"));
        resultMap.put("pay_channel", backMap.getString("pay_channel"));
        resultMap.put("bankCode", backMap.getString("bank_code"));
        resultMap.put("sysOrderId", paramMap.getString("pay_order"));
        resultMap.put("desc", paramMap.getString("pay_title"));
        resultMap.put("bankCardNo", paramMap.getString("bank_card_no"));
        resultMap.put("realName", paramMap.getString("bank_card_idname"));
        resultMap.put("certNo", paramMap.getString("bank_card_idcard"));
        resultMap.put("mpNumber", paramMap.getString("mpNumber"));
        resultMap.put("user_id", paramMap.getString("user_id"));
        resultMap.put("rech_type", paramMap.getString("rech_type"));
        resultMap.put("rech_channel", paramMap.getString("rech_channel"));
        return resultMap;

    }

    /**
     * 校验
     *
     * @param paramMap
     * @return boolean
     * @throws Exception
     */
    public static boolean validateResult(Map<String, Object> paramMap) throws Exception {
        QuickPayDTO quickOrder = parseOrder(paramMap);
        if (quickOrder == null || StringUtils.isBlank(quickOrder.getStatus())
                || !"100".equals(quickOrder.getStatus())) {
            return false;
        }
        return true;
    }

    /**
     * 获取接口配置信息
     *
     * @return BaoFooOrder
     * @throws Exception
     */
    public static QuickPayDTO generator(RechOrderDTO rechOrderDTO)
            throws Exception {
        if (rechOrderDTO == null || rechOrderDTO.getRechChannel() == null) {
            FrameUtil.throwBaseException1("参数异常");
        }

        QuickPayConfigDTO quickPayConfigDTO = QuickPayUtils.getConfig();
        RechChannel rechChannel = rechOrderDTO.getRechChannel();
        QuickPayDTO quickPayDTO = new QuickPayDTO();
        quickPayDTO.setAppUser(quickPayConfigDTO.getUser());
        quickPayDTO.setAppType(rechChannel.getAppType());
        quickPayDTO.setPayUrl(quickPayConfigDTO.getPayUrl());
        quickPayDTO.setReturnUrl(quickPayConfigDTO.getReturnUrl() + OriginRechChannel.getChannel(rechChannel.getLable()).getPageUrl());
        quickPayDTO.setCallBackUrl(quickPayConfigDTO.getCallbackUrl());
        quickPayDTO.setKey(quickPayConfigDTO.getKey());
        return quickPayDTO;
    }

    /**
     * 查询充值系统参数
     *
     * @return
     * @throws Exception
     */
    public static QuickPayConfigDTO getConfig() throws Exception {
        return JSON.parseObject(SysParamUtil.getValue(SysParamKeyEnum.MFQ_RECH_CONFIG),
                QuickPayConfigDTO.class);
    }

}
